
#include "utils.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void bb_fatal(char const* text)
{
    fprintf(stderr, "FATAL: %s\n", text);
    exit(1);
}

void bb_fatal_errno(char const* text)
{
    fprintf(stderr, "FATAL: %s (errno=%d strerror=%s)\n", text, errno, strerror(errno));
    exit(1);
}

void bb_current_time(struct timeval* output)
{
    gettimeofday(output, NULL);
}

void bb_format_time(struct timeval const* t, char* output)
{
    time_t timer = (time_t)t->tv_sec;
    struct tm* tm_info = localtime(&timer);
    strftime(output, 64, "%T", tm_info);
    sprintf(output + strlen(output), ".%03u", (unsigned)(t->tv_usec / 1000));
}

bool bb_is_file_or_dir_hidden(char const* name)
{
    char const* last_slash = rindex(name, '/');
    return (last_slash ? last_slash[1] : name[0]) == '.';
}

bool bb_is_source_file(char const* name)
{
    char const* suffix = rindex(name, '.');
    if (!suffix)
        return false;
    return (0 == strcmp(suffix, ".h")) || (0 == strcmp(suffix, ".hh")) ||
           (0 == strcmp(suffix, ".hpp")) || (0 == strcmp(suffix, ".inl")) ||
           (0 == strcmp(suffix, ".c")) || (0 == strcmp(suffix, ".cc")) ||
           (0 == strcmp(suffix, ".cpp"));
}

void bb_announce_event(struct timeval const* time, unsigned event_id, char const* message)
{
    char buffer[64];
    bb_format_time(time, buffer);
    printf("\033[1;32m---> [%s][%u] %s\033[1;37m\n", buffer, event_id, message);
}

